package com.zlx.mall.biz.access.holder;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.zlx.mall.basic.common.constant.Constants;
import com.zlx.mall.basic.common.exception.IllegalBizArgumentException;
import com.zlx.mall.basic.common.model.SystemParam;
import org.jetbrains.annotations.NotNull;

import java.util.Optional;
import java.util.function.Function;

/**
 * @author qingke
 **/
public class UserContextHolder {

    public static final TransmittableThreadLocal<SystemParam> SYSTEM_PARAM = new TransmittableThreadLocal<>();
    public static final TransmittableThreadLocal<Long> USER_ID = new TransmittableThreadLocal<>();

    static {
        ContextHolder.register(SYSTEM_PARAM);
        ContextHolder.register(USER_ID);
    }

    public static SystemParam getSystemParam() {
        return SYSTEM_PARAM.get();
    }

    public static void setSystemParam(SystemParam param) {
        SYSTEM_PARAM.set(param);
    }

    public static String getSystemParam(Function<SystemParam, String> function) {
        return Optional.ofNullable(getSystemParam())
                .map(function)
                .orElse(Constants.EMPTY_STRING);
    }

    public static void setUserId(Long userId) {
        USER_ID.set(userId);
    }

    @NotNull
    public static Long getUserId() {
        return Optional.ofNullable(USER_ID.get())
                .orElseThrow(() -> new IllegalBizArgumentException("Null User Session"));
    }

    public static void remove() {
        SYSTEM_PARAM.remove();
        USER_ID.remove();
    }

}
